import cloudbase from '@cloudbase/js-sdk';

/**
 * 云开发工具类
 * 封装常用的云开发操作
 */
class CloudbaseService {
  constructor() {
    this.app = null;
    this.auth = null;
    this.db = null;
    this.storage = null;
    this.initialized = false;
  }

  /**
   * 初始化云开发环境
   */
  async init() {
    if (this.initialized) {
      return;
    }

    try {
      // 初始化云开发SDK
      this.app = cloudbase.init({
        env: process.env.REACT_APP_CLOUDBASE_ENV_ID, // 环境ID，从环境变量中获取
      });

      // 初始化身份验证
      this.auth = this.app.auth({
        persistence: 'local', // 本地持久化登录状态
      });

      // 初始化数据库
      this.db = this.app.database();

      // 初始化云存储
      this.storage = this.app.storage();

      this.initialized = true;
      console.log('云开发环境初始化成功');
    } catch (error) {
      console.error('云开发环境初始化失败:', error);
      throw error;
    }
  }

  /**
   * 获取当前登录用户
   * @returns {Promise<Object|null>} 用户信息或null
   */
  async getCurrentUser() {
    if (!this.initialized) {
      await this.init();
    }

    try {
      const loginState = await this.auth.getLoginState();
      return loginState && loginState.user ? loginState.user : null;
    } catch (error) {
      console.error('获取当前用户失败:', error);
      return null;
    }
  }

  /**
   * 微信登录
   * @returns {Promise<Object>} 登录结果
   */
  async loginWithWechat() {
    if (!this.initialized) {
      await this.init();
    }

    try {
      const result = await this.auth.weixinAuthProvider().signIn();
      return {
        code: 0,
        message: '登录成功',
        user: result.user,
      };
    } catch (error) {
      console.error('微信登录失败:', error);
      return {
        code: -1,
        message: error.message || '微信登录失败',
      };
    }
  }

  /**
   * 匿名登录
   * @returns {Promise<Object>} 登录结果
   */
  async loginAnonymously() {
    if (!this.initialized) {
      await this.init();
    }

    try {
      const result = await this.auth.anonymousAuthProvider().signIn();
      return {
        code: 0,
        message: '匿名登录成功',
        user: result.user,
      };
    } catch (error) {
      console.error('匿名登录失败:', error);
      return {
        code: -1,
        message: error.message || '匿名登录失败',
      };
    }
  }

  /**
   * 退出登录
   * @returns {Promise<Object>} 退出结果
   */
  async logout() {
    if (!this.initialized) {
      await this.init();
    }

    try {
      await this.auth.signOut();
      return {
        code: 0,
        message: '退出登录成功',
      };
    } catch (error) {
      console.error('退出登录失败:', error);
      return {
        code: -1,
        message: error.message || '退出登录失败',
      };
    }
  }

  /**
   * 调用云函数
   * @param {string} name 云函数名称
   * @param {Object} data 云函数参数
   * @returns {Promise<Object>} 云函数执行结果
   */
  async callFunction(name, data = {}) {
    if (!this.initialized) {
      await this.init();
    }

    try {
      const result = await this.app.callFunction({
        name,
        data,
      });

      return result.result || {};
    } catch (error) {
      console.error(`调用云函数 ${name} 失败:`, error);
      throw error;
    }
  }

  /**
   * 上传文件到云存储
   * @param {File} file 文件对象
   * @param {string} cloudPath 云存储路径
   * @returns {Promise<Object>} 上传结果
   */
  async uploadFile(file, cloudPath) {
    if (!this.initialized) {
      await this.init();
    }

    try {
      const result = await this.storage.uploadFile({
        cloudPath,
        filePath: file,
      });

      // 获取文件访问链接
      const fileList = [
        {
          fileID: result.fileID,
          tempFileURL: '',
        },
      ];
      const { fileList: tempFileList } = await this.getTempFileURL(fileList);

      return {
        code: 0,
        message: '上传成功',
        fileID: result.fileID,
        url: tempFileList[0].tempFileURL,
      };
    } catch (error) {
      console.error('上传文件失败:', error);
      return {
        code: -1,
        message: error.message || '上传文件失败',
      };
    }
  }

  /**
   * 获取文件临时访问链接
   * @param {Array} fileList 文件ID列表
   * @returns {Promise<Object>} 文件访问链接
   */
  async getTempFileURL(fileList) {
    if (!this.initialized) {
      await this.init();
    }

    try {
      return await this.storage.getTempFileURL({
        fileList,
      });
    } catch (error) {
      console.error('获取文件访问链接失败:', error);
      throw error;
    }
  }

  /**
   * 删除云存储文件
   * @param {Array} fileList 文件ID列表
   * @returns {Promise<Object>} 删除结果
   */
  async deleteFile(fileList) {
    if (!this.initialized) {
      await this.init();
    }

    try {
      return await this.storage.deleteFile({
        fileList,
      });
    } catch (error) {
      console.error('删除文件失败:', error);
      throw error;
    }
  }
}

// 导出单例
export default new CloudbaseService();